import { useEffect, useState } from 'react';
import TikoCard from '../../component/TikoCard';
import TikoTypeButton from '../../component/TikoTypeButton';
import mySettingConfig from '../../config/mySettingConfig';
import myArrRequest from '../../util/myArrRequest';
import { hitokoto, type hitokotoType } from '../../type/hitokoto';
import getHitokotoUrl from '../../util/getHitokotoUrl';
import './main.css'
import useDebounceEffect from '../../hooks/useDebounceEffect';
function Main(): JSX.Element {
  const [myMap, setMyMap] = useState<Map<hitokotoType,boolean>>(new Map());
  const [myHitokotoArr,setMyHitokotoArr] = useState<hitokoto[]|null>(null);
  const [isLoading,setIsLoading] = useState(true);
  useEffect(
     ()=>{
          const TypeMap = new Map<hitokotoType,boolean>();
          mySettingConfig.myhitokotoType.forEach((value) => {
          TypeMap.set(value, true);
      })
         setMyMap(TypeMap)
     },[])
  useDebounceEffect(
    ()=>{  myArrRequest(getUrlArr(),mySettingConfig.requestInterval).then((res)=>{
           setMyHitokotoArr(res as hitokoto[])
           setIsLoading(false);
        })
    },[myMap],500)
  const refresh = () => {
    setIsLoading(true);
    setMyMap(new Map(myMap));
  }
  const changeTypeButton  = (type: hitokotoType): void => {
    //取反
    myMap.set(type, !myMap.get(type));
    setMyMap(new Map(myMap));
  }
  const getUrlArr = () => { 
     const urlArr = new Array(mySettingConfig.curNumber).fill(1).map(()=>
     getHitokotoUrl([...myMap.entries()].filter((v)=>v[1]).map(v=>v[0])))
     return urlArr;
  }
  return (
    <div className="Main">
      {isLoading ? <div className="LoadingBox">Loading.....</div>:(
      <div className="hitokotoBox">
        <div className='TikoTypeButtonBox'>
          {[...mySettingConfig.myhitokotoType].map(value =>
            <TikoTypeButton
              type={value}
              onClick={() => { changeTypeButton(value) }}
              isChoosed={myMap.get(value)} />)}
        </div>
        <div className="TikoCardBox">
        {myHitokotoArr?.map(v=><TikoCard hitokoto={v}/>)}
        </div>
      </div>
      )}
      <div className="refresh" onClick={refresh}>
        刷新
      </div>
    </div>
  );
}

export default Main;
